import React, { Component } from 'react';
import {
	StyleSheet, Text, FlatList,
	PixelRatio, View, Image, TouchableOpacity, DeviceEventEmitter
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import HTTP from '../../../utils/http';
import { NavigationEvents } from 'react-navigation';
import { SearchInput } from '../../../component/SearchInput.js';
import { orderBaseStyle } from './_common/style.js'
import { RangTime } from '../../../component/common/RangTime.js';
import { CURRENCY } from '../../../utils/helper';
import { Button } from '../../../components/form/button';
import ToastUtil from '../../../utils/toast';
const saleImage = require('../../../imgs/order/sale.png');
const purchaseImage = require('../../../imgs/order/purchase.png');

const scale = GLOBAL.SCALE;

let sendData = {
	onrefresh: false,
	pageNo: 1,
	pageSize: 20,
	orderType: 'S',
	searchKey: ''
};

export class historyOrderList extends Component {
	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '一键下单',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	requesting;
	constructor(props) {
		super(props);
		let { orderType, tCode } = this.props.navigation.state.params || {};
		sendData.orderType = orderType;
		sendData.tCode = tCode;
		this.state = {
			newLotData: [],  // 待审批
			status: 'loading',
			loadIcon: false,  // 下拉涮新的 图标
			applyIdChecked: {},
			timeModel: false,//时间显示,
			timeStart: null,
			timeEnd: null,
		}
		this.pageNo = 1;
		this.totalPage = 1;
	}

	componentWillMount () {
		this._getListData();
	}

	componentWillUnmount () {
		sendData.pageNo = 1;
	}



	//勾选函数
	_toggleUserIdChecked = (sendId) => {
		let { applyIdChecked } = this.state;
		let { tCode } = sendData;
		let val = applyIdChecked[sendId] ? 0 : 1;

		if (tCode != 'QH') {
			if (val) { // 勾选  去掉其它的
				for (var value in applyIdChecked) {
					if (value != sendId) {
						applyIdChecked[value] = 0;
					}
				}
			}
		}

		applyIdChecked[sendId] = val;
		this.setState({
			applyIdChecked
		});
	}

	//获取待审批,已审批列表
	async _getListData (agentObj) {
		const { timeStart, timeEnd } = this.state
		let { tCode } = sendData;
		this.setState({
			applyIdChecked: {}
		});

		Object.assign(sendData, agentObj);
		sendData.startDate = timeStart;
		sendData.endDate = timeEnd;
		sendData.noBid = 1; // 排除意向转单
		this.setState({
			loadIcon: true
		})
		let url = tCode == 'C' ? API.GET_ORDER_HISTORY_C : (tCode == 'QH' ? API.GET_ORDER_HISTORY_QH : API.GET_ORDER_HISTORY)
		if (tCode == 'A') {
			url = API.GET_ORDER_HISTORY_A;
		}

		let responseData = await HTTP.POST(API_GENERATE(url), sendData);
		this.setState({
			loadIcon: false
		});
		if (responseData) {
			this.totalPage = responseData.totalPage;
			if (sendData.onrefresh) {  // 加载
				this.setState({
					newLotData: this.state.newLotData.concat(responseData.rows),
					status: 'data'
				})
			} else { // 刷新
				this.setState({
					newLotData: responseData.rows,
					status: responseData.rows.length ? 'data' : 'empty'
				})
			}
		} else {
			this.setState({
				status: 'error'
			})
		}
	}

	// 下拉更新函数
	_isLoadRefresh () {
		this.pageNo = 1;
		sendData.onrefresh = false,
			this._getListData();
	}

	//上拉加载
	_loadData () {
		if (this.totalPage > this.pageNo) {
			this.pageNo++;
			this._getListData({
				pageNo: this.pageNo,
				onrefresh: true
			});
		}
	}

	//数据加载出错回调
	_onErrorPress = () => {
		this.setState({
			status: 'loading'
		}, function () {
			this._getListData();
		})
	}

	_addFn = () => {
		let { applyIdChecked } = this.state;
		let { tCode } = sendData;
		let resultId = null;
		let orderIdList = [];
		for (var value in applyIdChecked) {
			if (applyIdChecked[value] == 1) {
				resultId = value;
				orderIdList.push(value)
			}
		}
		DeviceEventEmitter.emit('historyFn', { isHistory: true });
		if (tCode == 'QH') {
			if (orderIdList && orderIdList.length <= 0) {
				ToastUtil.showWarning('请选择订单')
				return
			}
			this.props.navigation.navigate('HistoryOrderInfoPage', {
				orderIdList,
				orderList: this.qhOrderList || null,
				historyListcallBack: (data) => {
					this.historyQhcallBack(data)
				}
			});
		} else {
			if (!resultId) {
				ToastUtil.showWarning('请选择订单')
				return
			}
			this.props.navigation.navigate('orderBasePage', { orderId: resultId });
			this.props.navigation.state.params.hisCallback && this.props.navigation.state.params.hisCallback(resultId);
		}
	}

	historyQhcallBack = (data) => {
		let applyIdChecked = {};
		let { orderIdList, qhOrderList } = data;
		this.qhOrderList = qhOrderList;
		orderIdList.forEach(item => {
			applyIdChecked[item] = 1
		})
		this.setState({ applyIdChecked })
	}

	_cancelCall = () => {
		this.setState({
			timeModel: false
		})
	}

	_resultCall = (resultData) => {
		this.pageNo = 1;
		this.setState({ loading: true });
		this.setState({
			timeStart: resultData.startTime,
			timeEnd: resultData.endTime,
			timeModel: false
		}, () => {
			this._getListData({
				pageNo: this.pageNo,
				onrefresh: false
			});
		})
	}

	_renderItem (data) {
		let { orderId, bizMode, companyName, oppocompanyName, oppoOrderId, goodsNames, payTypeName, createTime, purchaseDeliveryTypeName, saleDeliveryTypeName, price, goodQuantity, uomName, currency, deliveryTypeName } = data.item;
		let { tCode } = sendData;
		let rightImg = tCode == 'QH' ? require('../../../imgs/global/checkBoxChecked.png') : require('../../../imgs/global/success.png');
		let emptyImg = tCode == 'QH' ? require('../../../imgs/global/checkBoxCancel.png') : require('../../../imgs/global/option.png');
		let unit = '';
		let unitSymbol = '';
		if (currency) {
			unit = CURRENCY.getUnit(currency).text;
			unitSymbol = CURRENCY.getUnit(currency).label;
		} else {
			unit = '元';
			unitSymbol = '￥';
		}
		const { applyIdChecked } = this.state;
		const optionSource = (applyIdChecked[orderId] && applyIdChecked[orderId] == 1) ? rightImg : emptyImg;
		return (
			<TouchableOpacity activeOpacity={.8} onPress={() => { this._toggleUserIdChecked(orderId) }} style={{ flex: 1, alignItems: 'center', marginTop: 10 * scale }}>
				<View style={styles.itemBox}>
					<View style={styles.itemBoxHead}>
						<View style={styles.bombBody} >
							<Image style={[styles.bombImg, applyIdChecked[orderId] && applyIdChecked[orderId] == 1 ? null : { tintColor: '#cdcdcd' }]} source={optionSource} />
							<Text style={styles.itemHeadTitle} numberOfLines={1} >{orderId || ''}</Text>
						</View>
						<Text style={styles.time}>{createTime}</Text>
					</View>
					<View style={styles.itemBody}>

						{
							tCode == 'C' ? (
								<View>
									<View style={styles.listItem}>
										<Text style={styles.lable}>企业</Text>
										<TouchableOpacity activeOpacity={.8} style={{ flexDirection: 'row', alignItems: 'center' }} onPress={() => { this.props.navigation.navigate('OrderDetailsPage', { orderId: oppoOrderId }) }}>
											<Image style={{ marginRight: 6 * scale }} source={purchaseImage} />
											<Text style={styles.value2}>{oppocompanyName}</Text>
										</TouchableOpacity>
									</View>
									<View style={[styles.listItem, { marginBottom: 6 * scale }]}>
										<Text style={styles.lable}></Text>
										<TouchableOpacity activeOpacity={.8} style={{ flexDirection: 'row', alignItems: 'center' }} onPress={() => { this.props.navigation.navigate('OrderDetailsPage', { orderId }) }}>
											<Image style={{ marginRight: 6 * scale }} source={saleImage} />
											<Text style={styles.value2}>{companyName}</Text>
										</TouchableOpacity>
									</View>
								</View>
							) : (
									<View style={styles.listItem}>
										<Text style={styles.lable}>企业</Text>
										<TouchableOpacity activeOpacity={.8} style={{ flexDirection: 'row', alignItems: 'center' }} onPress={() => { this.props.navigation.navigate('OrderDetailsPage', { orderId }) }}>
											<Text style={styles.value2}>{companyName}</Text>
										</TouchableOpacity>
									</View>
								)
						}


						<View style={[styles.listItem, { flexWrap: 'wrap' }]}>
							<Text style={styles.lable}>商品</Text>
							<Text style={styles.value} >{goodsNames && goodsNames.length > 22 ? goodsNames.substr(0, 22) + "..." : goodsNames}
							</Text>
						</View>
						{
							tCode == 'QH' ?
								<View style={styles.listItem}>
									<Text style={styles.lable}>下单量</Text>
									<Text style={styles.value}>{goodQuantity}{uomName || '--'} | {price || '--'} {unit}/{uomName}</Text>
								</View> :
								<View style={styles.listItem}>
									<Text style={styles.lable}>属性</Text>

									{
										tCode == 'C' ?
											<Text style={styles.value}>{payTypeName} | {deliveryTypeName}</Text>
											:
											<Text style={styles.value}>{payTypeName} | {sendData.orderType == 'P' ? purchaseDeliveryTypeName : saleDeliveryTypeName}</Text>
									}


								</View>
						}

					</View>
				</View>
			</TouchableOpacity>
		)
	}


	render () {
		let { status, timeModel, timeStart, timeEnd } = this.state;
		const searchLeft = require('../../../imgs/customer/searchLeft.png');
		return (
			<View style={{ flex: 1, backgroundColor: '#f5f5f5', }}>
				{/* <NavigationEvents onWillFocus={() => { this._getListData() }} /> */}
				<View style={styles.headBox}>
					<View style={styles.outSearch}>
						<View style={styles.nerSearch}>
							<SearchInput
								placeholder={'订单号/企业名称/商品'}
								inputLeftIcon={searchLeft}
								setKeyWord={(txt) => {
									sendData.searchKey = txt;
									if (txt.length == 0) {
										sendData.searchKey = null;
										this._getListData();
									}
								}}
								onSubmitEditing={(txt) => { this._getListData() }}
								inputViewStyle={styles.searchStyle}
							/>
						</View>
					</View>
				</View>
				<TouchableOpacity onPress={() => { this.setState({ timeModel: !timeModel }) }} style={styles.dateSelect}>
					<Image source={require('../../../imgs/time.png')} style={{ width: 14 * scale, height: 16 * scale }} ></Image>
					<Text style={styles.timeValue}>{timeStart || '开始时间'} / {timeEnd || '结束时间'}</Text>
				</TouchableOpacity>
				<View style={styles.listBox}>
					{
						status == 'data' ? (<FlatList
							data={this.state.newLotData}
							renderItem={(data) => this._renderItem(data)}
							refreshing={this.state.loadIcon}
							onRefresh={this._isLoadRefresh.bind(this)}
							onEndReachedThreshold={1}
							onEndReached={() => { this._loadData() }}
						/>) : <PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this._onErrorPress} />
					}
					{/* {status == 'data' ? <Text style={styles.btnText} onPress={() => { this._addFn() }}>添加</Text> : null} */}
					{status == 'data' ? (
						<View style={styles.btnWarp}>
							<Button text={'添加'} width={300} height={34} onPress={() => { this._addFn() }} />
						</View>
					) : null}
				</View>

				{timeModel ? <RangTime isVisible={true} markedDates={null} startTime={timeStart} endTime={timeEnd} resultCall={this._resultCall} closeCall={this._cancelCall} /> : null}
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#E2E6F1'
	},
	listBox: {
		flex: 1,
	},
	bombBody: {
		flexDirection: 'row',
		alignItems: 'center'
	},
	bombImg: {
		marginRight: 4 * scale,
		width: 14 * scale,
		height: 14 * scale,
	},
	headBox: {
		backgroundColor: style.color.themeColor,
		height: 55 * scale,
		// width: '100%',
	},
	outSearch: {
		height: 36 * scale,
		// width: '100%',
		flexDirection: 'row',
		justifyContent: 'center',
	},
	nerSearch: {
		height: 36 * scale,
		width: '80%'
	},
	searchStyle: {
		height: 36 * scale,
	},
	itemBox: {
		width: 350 * scale,
	},
	itemBoxHead: {
		height: 40 * scale,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center'
	},
	itemHeadTitle: {
		fontSize: 14 * scale,
		color: '#272727',
		paddingLeft: 3 * scale
	},
	itemBody: {
		backgroundColor: style.color.white,
		width: 350 * scale,
		borderRadius: 6 * scale,
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
		paddingLeft: 10 * scale,
		paddingRight: 10 * scale
	},
	listItem: {
		flexDirection: 'row',
		alignItems: 'center'
	},
	lable: {
		color: '#666',
		width: 50 * scale,
		fontSize: 13 * scale,
		lineHeight: 26 * scale
	},
	value: {
		color: '#111',
		fontSize: 13 * scale,
	},
	value2: {
		color: '#148CFB',
		fontSize: 13 * scale
	},
	time: {
		fontSize: 12 * scale,
		color: '#999'
	},
	btnText: {
		width: '80%',
		height: 40 * scale,
		lineHeight: 40 * scale,
		color: style.color.white,
		textAlign: 'center',
		backgroundColor: style.color.themeColor,
		marginLeft: '10%',
		borderRadius: 4 * scale,
		marginBottom: 15 * scale
	},
	dateSelect: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		marginRight: 14 * scale,
		marginTop: 12 * scale,
	},
	timeValue: {
		fontSize: 12 * scale,
		color: style.color.atrous,
		marginLeft: 8 * scale
	},
	btnWarp: {
		height: 72 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
	},
})